//
//  UIDevice(Identifier).m
//  UIDeviceAddition
//
//  Created by Georg Kitz on 20.08.11.
//  Copyright 2011 Aurora Apps. All rights reserved.
//

#import "UIDevice+IdentifierAddition.h"
#import "NSString+MD5Addition.h"
#import "KeychainItemWrapper.h"
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

@interface UIDevice(Private)

@end

@implementation UIDevice (IdentifierAddition)

////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Public Methods

- (NSString *) uniqueDeviceIdentifier{
    
    NSString* bundleId=[[NSBundle mainBundle] bundleIdentifier];
    
    KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc]
                                         
                                         initWithIdentifier:@"BSL_DEVICE_ID"
                                         
                                         accessGroup:nil];
    
    NSString *strUUID = [keychainItem objectForKey:(id)kSecValueData];
    
    if ([strUUID length]<1)
    {
        
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        
        strUUID = (NSString *)CFUUIDCreateString (kCFAllocatorDefault,uuidRef);
        [keychainItem setObject:strUUID forKey:(__bridge id)kSecAttrService];
        [keychainItem setObject:strUUID forKey:(id)kSecValueData];
        
        [strUUID release];
        CFRelease(uuidRef);
    }
    
    strUUID = [keychainItem objectForKey:(id)kSecValueData];
    
    NSString *stringToHash = [NSString stringWithFormat:@"%@%@",strUUID,bundleId];
    
    [keychainItem release];
    
    NSString *uniqueIdentifier = [stringToHash stringFromMD5];
        
    return uniqueIdentifier;
}


@end
